<template>
  <div>
    <div :style="{height:height+'px',width:width+'px'}" class="menu-wrapper">
      <div class="menu-title">
        <div class="title-line"></div>
        <div 
          :title="title" 
          :style="{'font-size': $attrs.fontSize,'font-weight' : $attrs.bold ? 'bold' : 'normal','font-style': $attrs.italic ? 'italic' : 'normal','text-decoration': $attrs.underline ? 'underline' : 'none','text-align': `${$attrs.textAlign}`,'color': `${$attrs.fontColor}`,'line-height': `${$attrs.lineHeight}`}"  
          class="title-name"
        >{{title}}</div>
        <div class="title-more" @click="jumpToPage">更多</div>
      </div>
      <el-table :data="tableData" stripe size="small" v-loading="tableLoading" class="tableInfo"
        v-if="fieldData.length>0">
        <el-table-column v-for="(item, idx) in tableFields" :key="idx" :label="item.name" :prop="item.field" :align="item.align"
          :width="item.colWidth" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="item.format==='datetime'">{{getDateTime(scope.row[item.field])}}</span>
            <span
              v-else-if="specialTypes.includes(item.tag)">{{getShowValue(scope.row[item.field],item.tag,item.dataType,item.options)}}</span>
            <span v-else-if="item.tag==='color'">
              <span :style="{background:scope.row[item.field],width:'10px',height:'10px',display:'inline-block'}"></span>
              {{scope.row[item.field]}}
            </span>
            <span v-else-if="item.tag==='upload'">{{getFileNames(scope.row[item.field])}}</span>
            <span v-else-if="item.tag==='password'">{{getPassword(scope.row[item.field])}}</span>
            <span v-else>{{scope.row[item.field]}}</span>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div style="width:100%;height:20px;"></div>
  </div>
</template>
<script>
  import {
    getListData,
    getAllListData
  } from "@/api/custom/formPoster";
  import {
    getFormInfo,
    getColumnData,
    getDictData
  } from '@/api/custom/formDesigner';
  import {
    getMenu
  } from '@/api/system/menu';
  import {
    regionData
  } from "element-china-area-data";
  import {getHomePage} from '@/api/login'
  const specialTypes = ['switch', 'cascader', 'place', 'select', 'radio', 'checkbox','tree-table']; //需处理后在table中展示
  export default {
    props: {
      width: { //宽度
        type: Number,
        default: '1000'
      },
      height: { //高度
        type: Number,
        default: '450'
      },
      title: { //标题
        type: String,
        default: '信息列表'
      },
      jumpTo: { //跳转功能
        type: Number,
        default: 0
      },
      maxRow: { //最大行数
        type: Number,
        default: 10
      },
      table: { //表名
        type: String,
        default: ''
      },
      sortField: { //排序字段
        type: String,
        default: 'createTime'
      },
      columns: { //列配置
        type: Array,
      },
      formName: { //表单id
        type: Number
      },
    },
    data() {
      return {
        tableLoading: false,
        tableData: [],
        tagIcons: [],
        fieldData: [],
        specialTypes: specialTypes,
        tableFields: []
      }
    },
    mounted() {
      this.getFormInfos()
    },
    watch: {
      maxRow(val) {
        this.getMessages()
      },
      sortField(val) {
        this.getMessages()
      },
      table(val) {
        this.getMessages()
      },
      formName(val) {
        this.getFormInfos()
      },
      columns: {
        handler(val) {
          this.getColumns()
        },
        deep: true
      }
    },
    methods: {
      //获取表单信息
      getFormInfos() {
        if (this.formName) {
          getFormInfo(this.formName).then((res) => {
            if (res.code === 0) {
              this.parseData(res)
            }
          })
        }
      },
      //解析表单配置
      async parseData(res) {
        let formConfData = JSON.parse(res.data.formJsonUser)
        let fields = JSON.parse(res.data.formJsonData).data
        await this.getTagIcons(formConfData.fields)
        this.fieldData = fields.map((item, index) => {
          return {
            name: item.desc,
            value: item.name,
            format: item.format,
            tag: this.tagIcons[index].tag,
            dataType: this.tagIcons[index].dataType,
            options: this.tagIcons[index].option
          }
        })
        this.getColumns() //获取排序后的列
        this.getMessages() //获取列表数据
      },
      //获取排序后的列
      getColumns() {
        if (this.columns.length === 0) {
          this.tableFields = []
        } else {
          this.tableFields = this.columns.map((data) => {
            if (data.field === 'create_time') {
              data.format = 'datetime';
            } else {
              let option = this.fieldData.filter((opt) => {
                return opt.value === data.field
              });
              data.format = option[0].format;
              data.dataType = option[0].dataType;
              data.tag = option[0].tag;
              data.options = option[0].options;
            }
          return data
          }).sort((a, b) => {
            return a.sortId - b.sortId
          })
        }
      },
      //获取列表数据
      getMessages() {
        this.tableData = []
        if (this.table) {
          this.tableLoading = true
          let params = {
            tableName: this.table,
            fieldName: this.sortField,
            order: 'desc',
            current: 1,
            size: this.maxRow,
            dataType: '2'
          }
          getListData(params).then((res) => {
            if (res.code === 0) {
              this.tableData = res.data.records
              this.tableLoading = false
            }
          }).catch(e => {
            console.log(e)
            this.tableLoading = false
          })
        }
      },
      //跳转
      async jumpToPage() {
        const flag = this.$store.state.currentStep.clickFlag
        if(flag){
          let toUrl = ''
          await getHomePage().then(res => {
            toUrl= res.data.path
          }).catch(error => {
            console.log(error)
          })
          let urls = []
          let res = null
          //根据菜单id，获取完整path
          while (true) {
            res = await getMenu(res ? res.data.parentId : this.jumpTo)
            if (res.code === 0) {
              if (res.data) {
                urls.push(res.data.path)
                if (res.data.parentId === 0) {
                  break
                }
              } else {
                break
              }
            }
          }
          if (urls.length > 0) {
            toUrl = urls.reverse().join('/')
          }
          this.$router.push(toUrl)
        }
      },
      //特殊类型组件数据展示
      getShowValue(data, tag, dataType, options) {
        if (!data) {
          return ''
        } //空数据
        if (tag === 'switch') {
          return data === options[0].toString() ? '是' : (data === options[1].toString() ? '否' : '')
        } else if (tag === 'place') {
          return data.split('(')[0]
        } else if (tag === 'checkbox' || tag === 'select' || tag === 'radio') {
          if (dataType === 'static') {
            let keys = data.split(',')
            if (keys.length > 1 && (tag === 'select' || tag === 'radio')) {
              return ''
            } else {
              let str = []
              options.length > 0 && keys.map((res, index) => {
                options.forEach((item) => {
                  if (item.label.toString() === res) {
                    str.push(item.label)
                    return true
                  }
                })
              })
              return str.join(',')
            }
          } else {
            return data
          }
        } else if (tag === 'cascader'|| tag === 'tree-table') {
          let keys = data.split(',')
          if (dataType === 'dynamic') {
            return keys.join('/')
          } else if (dataType === 'static') {
            let str = []
            let index = 0
            keys.length > 0 && this.getLabelByKey(options, keys, index, str)
            return str.join('/')
          } else if (dataType === 'region') {
            let str = []
            let index = 0
            keys.length > 0 && this.getLabelByKey(regionData, keys, index, str)
            return str.join('/')
          }
        }
      },
      //根据key值获取label
      getLabelByKey(options, key, index, str) {
        options.length > 0 && options.forEach((item) => {
          if (item.value.toString() === key[index]) {
            str.push(item.label)
            index++
            index < key.length && this.getLabelByKey(item.children, key, index, str)
            return true
          }
        })
      },
      //判断是否是json
      isJson(str) {
        if (typeof (str) === 'string') {
          try {
            var obj = JSON.parse(str)
            if (typeof (obj) === 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      //上传组件获取文件名
      getFileNames(data) {
        if (!data) {
          return ''
        } //空数据
        if (!this.isJson(data)) {
          return ''
        }
        let files = JSON.parse(data)
        return files.map((item) => {
          return item.name
        }).toString()
      },
      //时间戳转日期时间
      getDateTime(time) {
        if (!time) return ''
        let date = new Date(time)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
      },
      //密码隐藏
      getPassword(data) {
        if (!data) return ''
        let str = ''
        for (let i = 0; i < data.length; i++) {
          str += '*'
        }
        return str
      },
      //获取组件的tag,dataType和option
      async getTagIcons(data) {
        if (data.length === 0) return
        let comps = data.filter((item) => {
          return item.__config__.tag !== 'TitleLine' //过滤标题和分割线组件
        })
        for (let i = 0; i < comps.length; i++) {
          let item = comps[i]
          if (item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps' || item.__config__.tag ===
            'el-collapse') {
            //布局组件遍历内部子组件
            let tem = item.__config__.children.map((c) => {
              this.getTagIcons(c.__config__.children)
            })
          } else {
            let tag = item.__config__.tagIcon
            let options = []
            if (tag === 'switch') {
              options = [item['active-value'], item['inactive-value']]
              this.tagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options]
              })
            } else if (['select', 'radio', 'checkbox'].includes(tag)) {
              if (item.dataType === 'static') { //静态数据
                options = item.options
                this.tagIcons.push({
                  tag: tag,
                  dataType: item.dataType,
                  option: [...options]
                })
              } else if (item.dataType === 'dictionary' && item.dictName !== '') { //字典数据
                let res = await getDictData({
                  dictType: item.dictName
                })
                if (res.code === 0) {
                  res.data.forEach((item) => {
                    options.push({
                      label: item.label,
                      value: item.label
                    })
                  })
                }
                this.tagIcons.push({
                  tag: tag,
                  dataType: item.dataType,
                  option: [...options]
                })
              } else if (item.dataType === 'datasource' && item.tableName !== '' && item.fieldName !== '') { //动态数据
                let res = await getColumnData({
                  tableName: item.tableName,
                  column: item.fieldName,
                })
                if (res.code === 0) {
                  res.data.forEach((item) => {
                    options.push({
                      label: item,
                      value: item
                    })
                  })
                }
                this.tagIcons.push({
                  tag: tag,
                  dataType: item.dataType,
                  option: [...options]
                })

              }
            } else if (tag === 'cascader'|| tag === 'tree-table') {
              if (item.dataType === 'dynamic') { //动态数据
                await this.getDynamicOptions(item.fields,item.formName).then(res => {
                  options = res
                })
                this.tagIcons.push({
                  tag: tag,
                  dataType: item.dataType,
                  option: [...options]
                })
              } else if (item.dataType === 'static') { //静态数据
                options = item.options
                this.tagIcons.push({
                  tag: tag,
                  dataType: item.dataType,
                  option: [...options]
                })
              } else if (item.dataType === 'region') { //行政区域
                this.tagIcons.push({
                  tag: tag,
                  dataType: item.dataType,
                  option: regionData
                })
              }
            } else {
              this.tagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options]
              })
            }
          }
        }
      },
      //获取动态级联选项
      async getDynamicOptions(fields,formName) {
        let params = {
          tableName: formName,
          dataType: '2'
        }
       let res = await getAllListData(params)
       let options = []
       if (res.code === 0) {
        let tableData = res.data
        if (fields.length > 0) {
        for (let i = 0; i < fields[0].datas.length; i++) {
          let opt = fields[0].datas[i]
          let values = await getColumnData({
            tableName: formName,
            column: opt.fieldName,
          })
          values.data.map((item) => {
            let node = {
              label: item,
              value: item
            }
            let child = this.getChildren(opt.fieldName, item, 1,fields,tableData)
            if (child.length > 0) {
              node.children = child
            }
            options.push(node)
          })
        }
         }
         }
        return options
      },
      //获取子级选项
      getChildren(name, data, index,fields,tableData) {
        let option = []
        if (index >= fields.length) {
          return option
        } else {
          fields[index].datas.map((item) => {
            if (item.parent === name) {
              [...new Set(tableData.filter((field) => {
                return field[name] === data
              }).map((field)=>{return field[item.fieldName]}))].map((field) => {
                let node = {
                  label: field,
                  value: field
                }
                let child = this.getChildren(item.fieldName, field, index+1,fields,tableData)
                if (child.length > 0) {
                  node.children = child
                }
                option.push(node)
              })
            }
          })
          return option
        }
      },
    }
  }

</script>

<style lang="scss" scoped>
  .menu-wrapper {
    cursor: pointer;
    color: rgba(0, 0, 0, 0.45);
    font-size: 16px;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 5px;

    .menu-title {
      width: 100%;
      height: 40px;
      line-height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      .title-line {
        margin: 0 10px;
        width: 5px;
        height: 20px;
        background: #409eff;
      } 
      .title-name {
        width:calc(100% - 50px);
        padding-right:2% ;
        overflow:hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
      .title-more {
        width: 45px;
        float: right;
        right: 0px;
        color: #409eff;
      }
    }

    .tableInfo {
      margin: 10px 0px;
      padding: 0px 10px;
      height: calc(100% - 60px);
      overflow: auto;
    }

  }

</style>
<style lang='scss'>
  .menu-wrapper {
    .tableInfo {
      .el-table__cell {
        // border-bottom: 0px;
        padding: 0px;
      }

      .el-table__fixed {
        height: 100% !important;
      }

      .el-table__fixed-right {
        height: 100% !important;
      }

      .el-table__fixed::before {
        background-color: transparent;
      }

      .el-table__fixed-right::before {
        background-color: transparent;
      }
    }

    .el-table {
      box-sizing: border-box;

      &::before {
        height: 0px;
      }
    }

    .el-table--border::after,
    .el-table--group::after {
      width: 0px;
      height: 0px;
    }

  }

</style>
